package org.holdren.testspringmvc.config;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.holdren.testspringmvc.model.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.BeanNameViewResolver;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;
import org.springframework.web.servlet.view.xml.MarshallingView;

@Configuration
@ComponentScan(basePackages = "org.holdren.testspringmvc")
@EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter
{
	/*
	@Autowired
	private MarshallingView jaxbMarshaller;
	
	@Autowired
	private MappingJacksonJsonView jaxbJacksonObjectMapper;
	*/
	
	@Bean
	public ViewResolver getViewResolver()
	{
		InternalResourceViewResolver resolver = new InternalResourceViewResolver();
		resolver.setOrder(3);
		resolver.setPrefix("/WEB-INF/views/");
		resolver.setSuffix(".jsp");
		return resolver;
	}
	
	@Bean
	public ViewResolver getBeanNameViewResolver()
	{
		BeanNameViewResolver beanNameViewResolver = new BeanNameViewResolver();
		beanNameViewResolver.setOrder(2);
		return beanNameViewResolver;
	}
	
	@Bean
	public ViewResolver getContentNegotiatingViewResolver()
	{
		Map<String, String> mediaTypes = new HashMap<String, String>();
		mediaTypes.put("xml", "application/xml");
		mediaTypes.put("json", "application/json");
		
		Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
		jaxb2Marshaller.setClassesToBeBound(Person.class);
		
		MarshallingView marshallingView = new MarshallingView(jaxb2Marshaller);
		
		List<View> defaultViews = new ArrayList<View>();
		defaultViews.add(marshallingView);
		defaultViews.add(new MappingJacksonJsonView());
		
		ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
		resolver.setOrder(1);
		resolver.setIgnoreAcceptHeader(true);
		resolver.setMediaTypes(mediaTypes);
		resolver.setDefaultViews(defaultViews);
		
		return resolver;
	}

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry)
	{
		registry.addResourceHandler("/resources/**").addResourceLocations(
				"/resources/");
	}

}
